package cn.wolfcode.orderserver.controller;

import cn.wolfcode.orderapi.domain.Order;
import cn.wolfcode.orderserver.service.IOrderService;
import cn.wolfcode.productapi.domain.Product;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class OrderController {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @RequestMapping("/save")
    @HystrixCommand(fallbackMethod = "failMethod")
    public Order save(Long userId, Long productId, HttpServletRequest request) {
        log.info("执行了订单创建方法");
        //int i = 1 /0;

        //拿Cookie中的信息：默认会被zuul过滤掉
        String cookie = request.getHeader("cookie");
        String token = request.getHeader("token");
        System.out.println("cookie:" + cookie + "------------  token:" + token);

        return orderService.save(userId, productId);
    }

    //回退方法
    public Order failMethod(Long userId, Long productId, HttpServletRequest request) {
        log.info("执行了降级回退方法");
        //出现问题，执行该方法，可以利用该方法给开发人员发短信/邮件通知错误
        //20分钟发送一次，用Redis
        String key = "ORDER_FALL";
        String val = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(val)) {
            log.info("发送短信或者邮件");
            redisTemplate.opsForValue().set(key, "orderFall", 20, TimeUnit.SECONDS);
        } else {
            log.info("已经发送过了");
        }
        return new Order();
    }

}